<?php
   	require_once('../utils/logged_in.php');
	require_once('../utils/query.php');

	$cardIDs = $_POST["formvar"];

//HARD CODED VALUE FOR USER. NEEDS REAL USER ID HERE

$cardIDs = explode("~", $cardIDs);


//Get prices of cards
$price = 0;
$i = 0;

for($i=1;$i<count($cardIDs);$i++)
{
	$storeID = execute_query("SELECT storeitemid FROM StoreItemCards WHERE cardid='%s'", $cardIDs[$i]);
	if (!$storeID)
		continue;
	$storeID = mysql_result($storeID, 0);
	$iprice = execute_query("SELECT price FROM StoreItem WHERE storeitemid='%s'", $storeID);
	if (!$iprice)
		continue;
	$iprice = mysql_result($iprice, 0);
	$price = $price + $iprice; 
}


//Check how many points user has
$userPoints = 0;
$points_result = execute_query("SELECT points FROM untol1_testdru.druuserpoints WHERE uid = '%s' AND tid = 147", $drupaluid);
if ($points_result)
{
	$row = mysql_fetch_assoc($points_result);
	if ($row)
		$userPoints = $row['points'];
}

//hack for testing
$userPoints = 99999;


//Compare userpoints compared to price
//If has enough points
if($userPoints >= $price)
{
	//Insert the cards into the players possession
	$j = 0;
	for($j=1;$j<count($cardIDs);$j++)
	{
		$result = execute_query("INSERT INTO Possession (cardid, userid) VALUES ('%s', '%s')", $cardIDs[$j], $drupaluid);
	}
	
	//Deducte the price from the user if it went well
	if($result)
	{
		$result = execute_query("UPDATE untol1_testdru.druuserpoints SET points='%s' WHERE uid ='%s'", $userPoints - $price, $drupaluid);
	}
	echo "Transaction Complete";
}
//Did not have enough points
else
{
	echo "Not Enough Points";
}



?>
<html>
	<head></head>
	<body>

		<script language="JavaScript">
			self.location.href='../myCollection.php/'; 
		</script>

	</body>
</html>
